package model

import (
	"database/sql"

	"github.com/go-xorm/xorm"
)

// Book represents the t_book table.
type Book struct {
	ID        int64          `xorm:"'id' pk autoincr"`
	ISBN      string         `xorm:"'ISBN' notnull"`
	Price     string         `xorm:"'price'"`
	Name      string         `xorm:"'name'"`
	OthName   sql.NullString `xorm:"'othname' null"`
	Author    string         `xorm:"'author'"`
	OthAuthor string         `xorm:"'othauthor'"`
	PblTMS    sql.NullString `xorm:"'pbltms' null"`
	PblcOrgnz string         `xorm:"'pblcorgnz'"`
	Pblcty    string         `xorm:"'pblcty'"`
	Pbldate   string         `xorm:"'pbldate'"`
	Page      string         `xorm:"'page'"`
	BkSize    string         `xorm:"'bksize'"`
	OtherCnt  sql.NullString `xorm:"'othercnt' null"`
	Tgzy      sql.NullString `xorm:"'tgzy' null"`
	Title     sql.NullString `xorm:"'title' null"`
	TypeNb    string         `xorm:"'typenb'"`
	Gdh       sql.NullString `xorm:"'gdh' null"`
	IndxNb    string         `xorm:"'indxnb'"`
	Lrr       string         `xorm:"'lrr'"`
	Lrdate    string         `xorm:"'lrdate'"`
	Fname     sql.NullString `xorm:"'fname' null"`
	FAuthor   sql.NullString `xorm:"'fAuthor' null"`
	ControlNb sql.NullString `xorm:"'Controlnb' null"`
	FjNb      sql.NullString `xorm:"'fjnb' null"`
	FjName    sql.NullString `xorm:"'fjname' null"`
	TpSignal  string         `xorm:"'tpsignal'"`
	Yuzh      sql.NullString `xorm:"'yuzh' null"`
	Dgh       sql.NullString `xorm:"'dgh' null"`
	TyKh      sql.NullString `xorm:"'tykh' null"`
}

// TableName returns the name of the table in the database.
func (b Book) TableName() string {
	return "t_book"
}

// CreateBook creates a new record in the database.

// GetBook retrieves a record by ID from the database.
func GetBook(engine *xorm.Engine, id int) (*Book, error) {
	record := new(Book)
	has, err := engine.ID(id).Get(record)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, xorm.ErrNotExist
	}
	return record, nil
}

// UpdateBook updates a record in the database.
func UpdateBook(engine *xorm.Engine, newRecord *Book) error {
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	_, err := session.ID(newRecord.ID).Update(newRecord)
	if err != nil {
		if rErr := session.Rollback(); rErr != nil {
			return rErr
		}
		return err
	}
	if err := session.Commit(); err != nil {
		return err
	}
	return nil
}
